<template>
  <div class="max-w-7xl mx-auto p-4" v-if="!loading">
    <!-- 头部歌单信息 -->
    <div class="flex gap-8 mb-10">
      <div class="shrink-0">
        <img
          :src="playlistInfo.coverUrl"
          alt="歌单封面"
          class="w-48 h-48 object-cover rounded-lg"
        />
      </div>
      <div class="flex-1">
        <h1 class="text-2xl font-bold">{{ playlistInfo.name }}</h1>
        <div class="mt-4 flex items-center gap-2">
          <button
            @click="handlePlayAll"
            class="h-10 flex items-center gap-2 px-3 bg-gray-200 text-gray-900 rounded hover:bg-gray-300 transition-colors duration-200"
          >
            <IconPlay class="w-5 h-5" />
            <span class="text-sm font-semibold">播放全部</span>
          </button>
          <button
            @click="handleFavorite"
            class="flex items-center px-4 py-2 h-10 bg-gray-200 rounded text-red-500"
          >
            <IconHeart class="w-5 h-5" v-if="!isFavorite" />
            <IconHeartFilled class="w-5 h-5" v-else />
          </button>
        </div>
        <div class="mt-2 flex items-center gap-4">
          <!-- <span class="text-sm text-gray-500"
            >分类：{{ playlistInfo.category }}</span
          > -->
          <span class="text-sm text-gray-500"
            >创建于 {{ formatDate(playlistInfo.createTime) }}</span
          >
        </div>
        <p class="mt-4 text-gray-600 text-sm">{{ playlistInfo.description }}</p>
      </div>
    </div>

    <!-- 导航栏 -->
    <div class="mt-8">
      <Navbar :items="tabs" v-model="activeTab" />
    </div>

    <!-- 内容区域 -->
    <div class="mt-6">
      <!-- 歌曲列表 -->
      <div v-show="activeTab.id === 'songs'">
        <SongList :songs="playlistInfo.songs" :show-header="false" />
      </div>

      <!-- 评论区 -->
      <div v-show="activeTab.id === 'comments'" class="mt-6">
        <CommentSection
          :comments="comments"
          :playlist-id="playlistInfo.id"
          @comment-added="refreshComments"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { IconPlay, IconHeart, IconHeartFilled } from "@/components/icons";
import CommentSection from "@/components/CommentSection.vue";
import Navbar from "@/components/Navbar.vue";
import SongList from "@/components/SongList.vue";
import { ElMessage } from "element-plus";
import { usePlaylistAPI } from "@/services/playlist";
import { useUserStore } from "@/stores/user";
import { useCommentAPI } from "@/services/comment";
import { usePlayerStore } from "@/stores/player";
const userStore = useUserStore();
const playerStore = usePlayerStore();

const router = useRouter();
const route = useRoute();
const playlistAPI = usePlaylistAPI();
const commentAPI = useCommentAPI();

interface PlaylistInfo {
  id: string;
  name: string;
  description: string;
  category: string;
  coverUrl: string;
  playCount: number;
  createTime: string;
  songs: Array<{
    id: string;
    name: string;
    coverUrl: string;
    artist: {
      name: string;
    };
  }>;
}

const playlistInfo = ref<PlaylistInfo>({
  id: "",
  name: "",
  coverUrl: "",
  playCount: 0,
  category: "",
  createTime: "",
  description: "",
  songs: [],
});

const comments = ref([]); // 将现有的空数组初始化移到这里
const tabs = [
  { id: "songs", name: "歌曲列表" },
  { id: "comments", name: "评论" },
];

const activeTab = ref(tabs[0]);
const isFavorite = ref(false);
const isLoading = ref(false);
const loading = ref(true);

const goToSongDetail = (songId: number) => {
  router.push(`/song/${songId}`);
};

const handleFavorite = async () => {
  if (isLoading.value || !userStore.uid) return;
  isLoading.value = true;
  const originalStatus = isFavorite.value;
  isFavorite.value = !isFavorite.value; // 立即切换状态

  try {
    if (originalStatus) {
      await playlistAPI.postRemoveFromFavorite(
        userStore.uid,
        playlistInfo.value.id
      );
      ElMessage.success("已取消收藏");
    } else {
      await playlistAPI.postAddToFavorite(userStore.uid, playlistInfo.value.id);
      ElMessage.success("收藏成功");
    }
  } catch (error) {
    console.error("操作失败:", error);
    isFavorite.value = originalStatus; // 失败时恢复原始状态
    ElMessage.error(originalStatus ? "取消收藏失败" : "收藏失败");
  } finally {
    isLoading.value = false;
  }
};

// 修改播放全部处理函数
const handlePlayAll = () => {
  if (playlistInfo.value.songs.length > 0) {
    // 获取第一首歌
    const firstSong = playlistInfo.value.songs[0];
    // 播放第一首歌并设置整个歌单作为播放列表
    playerStore.playSong(firstSong, playlistInfo.value.songs);
  }
};

// 刷新评论列表
const refreshComments = async () => {
  try {
    const { data } = await commentAPI.getCommentByListId(
      route.params.id as string
    );
    if (data) {
      comments.value = data;
    }
  } catch (error) {
    console.error("获取评论失败:", error);
  }
};

const formatDate = (dateStr: string) => {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  return date.toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });
};

onMounted(async () => {
  const playlistId = route.params.id as string;
  try {
    loading.value = true;
    const [playlistResponse, commentResponse, musicResponse] =
      await Promise.all([
        playlistAPI.getPlaylistDetail(playlistId),
        commentAPI.getCommentByListId(playlistId),
        playlistAPI.getPlaylistMusic(playlistId),
      ]);

    playlistResponse.coverUrl =
      playlistResponse.coverUrl ||
      "https://xirealm.oss-cn-beijing.aliyuncs.com/xi/20250528224042.png";
    playlistInfo.value = playlistResponse;

    comments.value = commentResponse.data || [];
    // 更新歌曲列表
    playlistInfo.value.songs = musicResponse.data || [];

    playlistInfo.value.songs = musicResponse.data.map((item: any) => ({
      id: item.music.musicId,
      name: item.music.musicName,
      artist: item.music.musicAuthor,
      typeId: item.music.musicTypeId,
      url: item.music.musicUrl,
      cover:
        item.music.musicCoverUrl ||
        "https://xirealm.oss-cn-beijing.aliyuncs.com/xi/20250528224042.png",
      length: item.music.musicLength,
      status: item.music.status,
      score: item.music.musicAverageScore,
      lyric: item.music.lyric,
      isFavorite: item.favorStatus,
    }));

    // 获取收藏状态
    if (userStore.uid) {
      const favoriteStatus = await playlistAPI.checkIsFavorite(
        userStore.uid,
        playlistId
      );
      isFavorite.value = favoriteStatus;
    }
  } catch (error) {
    console.error("获取数据失败:", error);
  } finally {
    loading.value = false;
  }
});
</script>


<style scoped>
:deep(.el-table) {
  --el-table-border-color: transparent;
  --el-table-bg-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-hover-bg-color: #f9fafb;
}

:deep(.el-table__inner-wrapper::before) {
  display: none;
}

:deep(.el-table__cell) {
  border-bottom: none;
}

:deep(.el-table__row) {
  border-radius: 8px;
}
</style>

